// bp.c - 断点管理
#include <stdio.h>
#include <stdint.h>
#include "bp.h"

#define MAXBP 32
static bp_t bp_arr[MAXBP];
static int bp_cnt = 0;
pid_t pid_global = 0;   // 由 main.c 初始化

int bp_set(pid_t pid, uintptr_t addr) {
    if (bp_cnt >= MAXBP) return -1;
    uint64_t word = ptrace_read(addr);
    if (word == (uint64_t)-1) return -1;
    bp_arr[bp_cnt].addr  = addr;
    bp_arr[bp_cnt].saved = word;
    bp_arr[bp_cnt].enabled = 1;
    if (ptrace_write(addr, (word & ~0xFF) | 0xCC) < 0) return -1;
    printf("Breakpoint #%d at 0x%lx\n", bp_cnt, addr);
    bp_cnt++;
    return bp_cnt - 1;
}

bp_t* bp_find(uintptr_t addr) {
    for (int i = 0; i < bp_cnt; i++)
        if (bp_arr[i].enabled && bp_arr[i].addr == addr) return &bp_arr[i];
    return 0;
}